import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:zhibao_flutter/util/func/log.dart';
import 'package:zhibao_flutter/util/ui/my_toast.dart';

/// 获取内存图片缓存
double getMemoryImageCache() {
  return PaintingBinding.instance.imageCache.maximumSize / 1000;
}

/// 清除内存图片缓存
void clearMemoryImageCache() {
  PaintingBinding.instance.imageCache.clear();
}

/// 字符串转保留位数
String stringAsFixed(value, num) {
  double v = double.parse(value.toString());
  String str = ((v * 100).floor() / 100).toStringAsFixed(2);
  return str;
}

/// 隐藏手机号
String hiddenPhone(String phone) {
  String result = '';

  if (phone != null && phone.length >= 11) {
    String sub = phone.substring(0, 3);
    String end = phone.substring(7, 11);
    result = '$sub****$end';
  }

  return result;
}

/// 隐藏用户名
String hiddenUserName(String userName) {
  String result = '';

  if (userName != null && userName.length >= 3) {
    String sub = userName.substring(0, 2);
    String end = userName.substring(2, 3);
    result = '$sub****$end';
  }

  return result;
}

/// 隐藏微叉
String hiddenWekaka(String? value) {
  String result = '';

  if (value != null && value.length >= 3) {
    String sub = value.substring(0, 2);
    String end = value.substring(value.length - 1, value.length);
    result = '$sub****$end';
  }

  return result;
}

/// 去除后面的0
String stringDisposeWithDouble(v, [fix = 0, bool isRound = true]) {
  if (v == null) return '0';
  double b = double.parse(v.toString());
  String vStr;
  if (isRound) {
    vStr = b.toStringAsFixed(fix);
  } else {
    vStr = v.toString().substring(0, v.toString().indexOf('.'));
  }
  int len = vStr.length;
  for (int i = 0; i < len; i++) {
    if (vStr.contains('.') && vStr.endsWith('0')) {
      vStr = vStr.substring(0, vStr.length - 1);
    } else {}
  }

  if (vStr.endsWith('.')) {
    vStr = vStr.substring(0, vStr.length - 1);
  }

  return vStr;
}

/// 距离大于1000 显示km
String stringDisposeToKm(v) {
  if (v == null) return '0';
  int distance = double.parse(v.toString()).ceil();
  String d = distance
      .toString()
      .substring(0, v.toString().length > 3 ? v.toString().length - 3 : 0);
  if (distance > 1000) {
    int num = int.parse(distance
        .toString()
        .substring(distance.toString().length - 3, distance.toString().length));
    if (num >= 500) {
      return (int.parse(d) + 1).toString() + "km";
    }
    return d + "km";
  } else {
    return v + "m";
  }
}

/// 数字千分位方法及其价格保留两位小数
String formatNum(num, {point = 2, bool isMark = true}) {
  if (num != null) {
    String str = double.parse(num.toString()).toString();
    List<String> sub = str.split('.');
    List val = List.from(sub[0].split(''));
    List<String> points = List.from(sub[1].split(''));
    if (isMark) {
      for (int index = 0, i = val.length - 1; i >= 0; index++, i--) {
        //  && i != 1
        if (index % 3 == 0 && index != 0) val[i] = val[i] + ',';
      }
    }
    for (int i = 0; i <= point - points.length; i++) {
      points.add('0');
    }
    if (points.length > point) {
      points = points.sublist(0, point);
    }
    if (points.length > 0) {
      return '${val.join('')}.${points.join('')}';
    } else {
      return val.join('');
    }
  } else {
    return "0.0";
  }
}

/// 数字天数转中文实际天数
String limitToMonth(int limit) {
  if (limit == null || limit == 0) return '0天';
  switch (limit) {
    case 7:
      return '一周';

    case 14:
      return '两周';

    case const (1 * 30):
      return '一个月';
    case const (2 * 30):
      return '2个月';

    case const (6 * 30):
      return '半年';

    case const (12 * 30):
      return '一年';

    default:
      return '$limit天';
  }
}

/// 工作年限
String workYearStr(workYear) {
  if (workYear == null) return '0';
  try {
    Duration duration = DateTime.parse(workYear).difference(DateTime.now());
    String result = stringDisposeWithDouble(duration.inDays / 365, 0);
    return result.replaceAll('-', '');
  } catch (e) {
    LogUtil.d("出现错误::${e.toString()}");
    return '0';
  }
}

/// 去除小数点
String removeDot(v) {
  String vStr = v.toString().replaceAll('.', '');

  return vStr;
}

/// 补齐数字两位
String doubleNum(v) {
  int _v;
  if (v is int) {
    _v = v;
  } else {
    _v = int.parse(removeDot(v));
  }
  if (_v <= 0) {
    return '00';
  } else if (_v.toString().length < 2) {
    return '0$_v';
  } else {
    return '$_v';
  }
}

/// 万单位
String tenThousandUnits(v, [int point = 0]) {
  int _v;
  if (v is String && v == '') {
    _v = 0;
  } else {
    _v = int.parse(v?.toString() ?? '0');
  }
  if (_v < 10000) {
    double _double = double.parse('$_v.0');
    return '${_double.toStringAsFixed(point)}';
  } else if (_v >= 10000 && _v < 99999) {
    String str = '$_v';
    String substring = '.' + str.substring(1, 3);

    return '${str.substring(0, 1)}${subThousandUnitsZero(substring)}w';
  } else if (_v >= 100000 && _v <= 999999) {
    String str = '$_v';
    return '${str.substring(0, 2)}.${str.substring(2, 4)}w';
  } else if (_v >= 1000000 && _v <= 9999999) {
    String str = '$_v';
    return '${str.substring(0, 3)}w';
  } else if (_v >= 10000000 && _v <= 99999999) {
    String str = '$_v';
    return '${str.substring(0, 4)}w';
  } else {
    return '$_v';
  }
}

String subThousandUnitsZero(String substring) {
  String _substring = substring;
  if (_substring == '.00') {
    _substring = '';
  } else if (_substring.endsWith('0')) {
    _substring = _substring.substring(0, 2);
  }
  return _substring;
}

String subZeros(String value) {
  String _value = value;
  if (_value.endsWith('.00')) {
    _value.replaceAll('.00', '');
  } else if (_value.endsWith('.00')) {
    _value.replaceAll('.0', '');
  }
  return _value;
}

/// 将字符串切割成金额样式  比如1000000转成1.000.000  或  200000转成200.000
/// 也可以将所有的.替换成,   这样就是以,分隔 比如1,000,000或者200,000
String getMoneyStyleStr(String text) {
  try {
    if (text == null || text.isEmpty) {
      return "";
    } else {
      String temp = "";
      if (text.length <= 3) {
        temp = text;
        return temp;
      } else {
        int count = ((text.length) ~/ 3); //切割次数
        int startIndex = text.length % 3; //开始切割的位置
        if (startIndex != 0) {
          if (count == 1) {
            temp = text.substring(0, startIndex) +
                "." +
                text.substring(startIndex, text.length);
          } else {
            temp = text.substring(0, startIndex) + "."; //第一次切割0-startIndex
            int syCount = count - 1; //剩余切割次数
            for (int i = 0; i < syCount; i++) {
              temp +=
                  text.substring(startIndex + 3 * i, startIndex + (i * 3) + 3) +
                      ".";
            }
            temp += text.substring(
                (startIndex + (syCount - 1) * 3 + 3), text.length);
          }
        } else {
          for (int i = 0; i < count; i++) {
            if (i != count - 1) {
              temp += text.substring(3 * i, (i + 1) * 3) + ".";
            } else {
              temp += text.substring(3 * i, (i + 1) * 3);
            }
          }
        }
        return temp;
      }
    }
  } catch (e) {
    debugPrint(e.toString());
    return '';
  }
}

/// 四舍五入并保留两位小数
String keepTowAndRound(String value) {
  int oldIntValue = int.parse(value.substring(0, value.indexOf('.')));

  // 开始和结束
  int startIndex = value.indexOf('.') + 1;
  int endIndex = value.indexOf('.') + 4;

  int oldLength = value.substring(startIndex, value.length).length;
  bool isCount = oldLength > 2;
  if (!isCount) {
    return '${oldLength == 1 ? '${value}0' : value}';
  }

  // 开始计算
  String totalValue = value.substring(startIndex, endIndex);
  String endValue =
      totalValue.substring(totalValue.length - 1, totalValue.length);

  int oldIntValueEnd = int.parse(totalValue.substring(0, 2));

  int endValueInt = int.parse(endValue);
  if (endValueInt >= 5) {
    int rightValue = oldIntValueEnd + 1;
    int rightResult = rightValue >= 100 ? 00 : rightValue;
    int left = rightValue >= 100 ? oldIntValue + 1 : oldIntValue;
    return '$left.$rightResult';
  } else {
    return '$oldIntValue.$oldIntValueEnd';
  }
}

/// 秒转播放时长，如：00:00
String secondToPlayTime(String? time, [bool isInMilliseconds = false]) {
  if (time == null || time == '' || time == '0') {
    return '00:00';
  }
  int playTimeValue = int.parse(time);
  if (isInMilliseconds) {
    playTimeValue = playTimeValue ~/ 1000;
  }
  if (playTimeValue < 60) {
    return '00:${playTimeValue < 10 ? '0$playTimeValue' : playTimeValue}';
  } else {
    int inMinute = playTimeValue ~/ 60;
    String minuteStr = '${inMinute < 10 ? '0$inMinute' : inMinute}';

    int inSecond = playTimeValue % 60;
    String secondStr = '${inSecond < 10 ? '0$inSecond' : inSecond}';

    return '$minuteStr:$secondStr';
  }
}

Future copyText(String text, [String? tips]) async {
  final String str = text;
  await Clipboard.setData(ClipboardData(text: str));
  mySuccessToast(tips ?? "复制成功");

  LogUtil.d("复制文本：$text");
}

Future<String?> getCopyText() async {
  final ClipboardData? clipboardData =
      await Clipboard.getData(Clipboard.kTextPlain); //获取粘贴板中的文本
  return clipboardData?.text;
}

int myNext(int min, int max) {
  int res = min + Random().nextInt(max - min);
  return res;
}

extension BoolOpsation on bool {
  bool not() => !this;
}
